﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using LKVMLMLib;
using TrucTiepService;
using System.Data.Entity.SqlServer;
using System.Web.Mvc;
using System.Linq.Expressions;
using System.Globalization;
using TrucTiepService.Common;

namespace HoaHongTrucTiep
{
    public class ExecuteCommission
    {
        public void executeDirectly(int user_id, double amount, int? pv, int? OrderID, DateTime? date = null)
        {
            string connection = DuAnDaCapEntities.getDomain();
            var db = LKVMLMLib.DuAnDaCapEntities.initDuAnDaCapEntities(connection);
            var user = db.UserProfiles.Where(w => w.UserId == user_id).FirstOrDefault();
            // moi them
            if (user == null) return;
            var order = db.Orders.Where(w => w.ID == OrderID).SingleOrDefault();
            if (order == null) return;
            int floor = 1; //3 tầng ăn hoa hồng : F1:10% | F2: 3% | F3: 2 %
            var parent = db.UserProfiles.Where(w => w.UserId == user.Parent_ID).FirstOrDefault();
            double receiveamount = 0;
            while (floor < 4 && parent != null)
            {

                int lv = 0;
                if (floor == 1)
                    lv = 10;
                else if (floor == 2)
                    lv = 3;
                else
                    lv = 2;
                if (parent.Status != true || parent.UserName =="root")
                    continue;
                if (floor == 1)
                {
                    receiveamount = (lv * amount) / 100;
                }else if(floor == 2)
                {
                    receiveamount = (lv * amount) / 100;
                }
                else
                {
                    receiveamount = (lv * amount) / 100;
                }
                string desc = string.Format("Sponsor commission from reffer user {0}, order {1}.You recieve {2} % of Ph value, floor {3}", user.UserName, order.ID_Order,lv,floor);
                   
                    db.Profits.Add(new LKVMLMLib.Profit()
                    {
                        UserId = parent.UserId,
                        PV = 0,
                        Amount = receiveamount,
                        CreateDate = date,
                        Decription = desc,
                        ProfitType = "HoaHongTrucTiep",
                        OrderID = OrderID
                    });

                var refwallet = db.Wallet_Detail.Where(w => w.UserID == parent.UserId && w.WalletID == 1).SingleOrDefault();
                if (refwallet != null)
                {
                    refwallet.Balance += (double)receiveamount/2;
                    var walletHistory = new WalletHistory();
                    walletHistory.UserId = Convert.ToInt32(parent.UserId);
                    walletHistory.Amount = receiveamount/2;
                    walletHistory.CreateDate = DateTime.Now;
                    walletHistory.WalletId = 1;
                    walletHistory.Description = desc;
                    db.WalletHistories.Add(walletHistory);
                }
                var refwallet2 = db.Wallet_Detail.Where(w => w.UserID == parent.UserId && w.WalletID == 2).SingleOrDefault();
                if (refwallet != null)
                {
                    refwallet2.Balance += (double)receiveamount/2;
                    var walletHistory2 = new WalletHistory();
                    walletHistory2.UserId = Convert.ToInt32(parent.UserId);
                    walletHistory2.Amount = receiveamount / 2;
                    walletHistory2.CreateDate = DateTime.Now;
                    walletHistory2.WalletId = 1;
                    walletHistory2.Description = desc;
                    db.WalletHistories.Add(walletHistory2);
                }
                parent = db.UserProfiles.Where(w => w.UserId == parent.Parent_ID).FirstOrDefault();
                floor++;
            }
            db.SaveChanges();
        }
        public void executeDaily(DateTime date)
        {
            if (date == null) date = DateTime.Now;
            string connection = DuAnDaCapEntities.getDomain();
            var db = LKVMLMLib.DuAnDaCapEntities.initDuAnDaCapEntities(connection);
            var ps = PinService.MaThePaymentEntities.initMaThePaymentEntities(connection);
            var ls = db.UserProfiles.Where(w=>w.Status == true && w.IsFirst == false).ToList();
            if(ls.Count() > 0)
            {
                try {
                    foreach (var item in ls)
                    {
                        if (item.UserName.Equals("root"))
                            continue;
                        // lấy số lượng pin hiện có
                        var countPin = ps.MaThes.Where(w => w.UserId == item.UserId && w.Used != true).ToList();
                        //lấy pin sử dụng gần nhất
                        var lateUsePin = db.MaThes.Where(w => w.UserId == item.UserId && w.Used == true && w.UsedDate != null).OrderBy(o => o.UsedDate).ToList().LastOrDefault();
                        if (lateUsePin == null)
                            continue;
                        //khi kích pin tới ngày thứ 7 sẽ tự động kích pin và tạo PH
                        var needDate = lateUsePin.UsedDate.Value.Date.AddDays(7);
                        if (countPin.Count() >= 2)
                        {
                            if (needDate.Date == date.Date || date.Date > needDate.Date)
                            {
                                //đủ điều kiện thì kích pin và tạo PH
                                //lấy pin đăng ký lâu nhất mà chưa sử dụng
                                var pn = db.MaThes.Where(w => w.UserId == item.UserId && w.Used != true).OrderBy(o => o.CreateDate).FirstOrDefault();
                                pn.Used = true;
                                pn.UsedDate = DateTime.Now;
                                pn.UsedType = "Create PH";
                                var pinHis = new PinService.PinHistory();
                                pinHis.Amount = 1;
                                pinHis.Code = pn.Series;
                                pinHis.CreateDate = DateTime.Now;
                                pinHis.Description = "Active pin for PH";
                                pinHis.Collection = pn.Series;
                                pinHis.Type = 1;
                                ps.PinHistories.Add(pinHis);
                                ps.SaveChanges();
                                // tạo PH
                                var pg = db.Packages.OrderBy(o => o.ID).FirstOrDefault();
                                var ph = new PH();
                                ph.UserId = item.UserId;
                                ph.Status = 0;//New
                                ph.Amount = pg.Price;
                                ph.CreateDate = DateTime.Now;
                                ph.Delivered = 0;
                                ph.Extant = pg.Price;
                                db.PHs.Add(ph);
                                db.SaveChanges();
                                //Thêm 10% giá trị pin(15k) vào ví cộng đồng// edit thành 30%
                                var wl = db.WalletPublics.FirstOrDefault();
                                wl.Balance += 45000;
                                var wh = new WalletPublic_History();
                                wh.UserId = item.UserId;
                                wh.Value = 45000;
                                wh.Reason = pn.Series;
                                wh.Description = "Add 45000 as " + item.UserName + " activation pin <" + pn.Series + ">";
                                wh.CreateDate = DateTime.Now;
                                db.WalletPublic_History.Add(wh);
                                db.SaveChanges();
                            }
                        } else
                        {
                            //qua 7 ngày khóa tài khoản
                            if (needDate.Date < date.Date)
                            {
                                //item.Status = false;
                                //db.SaveChanges();
                            }

                        }
                    }
                }catch(Exception em) { }
            }
        }
        public void executeRemake(DateTime date)
        {
            try
            {
                string connection = DuAnDaCapEntities.getDomain();
                var db = LKVMLMLib.DuAnDaCapEntities.initDuAnDaCapEntities(connection);
                var lsorder = db.Orders.Where(w => w.Date != null && w.Action == true).ToList();
                foreach (var od in lsorder)
                {
                    var user = db.UserProfiles.FirstOrDefault(f => f.UserId == od.UserId.Value);
                    var parent = db.UserProfiles.Where(w => w.UserId == user.Parent_ID).FirstOrDefault();
                    if (parent != null && parent.UserName != "root" && parent.Status == true)
                    {
                        string desc = string.Format("Sponsor commission from reffer user {0}, order {1}.You recieve {2} % of Ph value, floor {3}", user.UserName, od.ID_Order, 10, 1);
                        db.Profits.Add(new LKVMLMLib.Profit()
                        {
                            UserId = parent.UserId,
                            PV = 0,
                            Amount = od.Amount.Value * 0.1,
                            CreateDate = od.Date,
                            Decription = desc,
                            ProfitType = "HoaHongTrucTiep",
                            OrderID = od.ID
                        });

                        var refwallet = db.Wallet_Detail.Where(w => w.UserID == parent.UserId && w.WalletID == 1).SingleOrDefault();
                        if (refwallet != null)
                        {
                            refwallet.Balance += (double)(od.Amount.Value * 0.1) / 2;
                            var walletHistory = new WalletHistory();
                            walletHistory.UserId = Convert.ToInt32(parent.UserId);
                            walletHistory.Amount = (od.Amount.Value * 0.1) / 2;
                            walletHistory.CreateDate = od.Date.Value;
                            walletHistory.WalletId = 1;
                            walletHistory.Description = desc;
                            db.WalletHistories.Add(walletHistory);
                        }
                        var refwallet2 = db.Wallet_Detail.Where(w => w.UserID == parent.UserId && w.WalletID == 2).SingleOrDefault();
                        if (refwallet != null)
                        {
                            refwallet2.Balance += (double)(od.Amount.Value * 0.1) / 2;
                            var walletHistory2 = new WalletHistory();
                            walletHistory2.UserId = Convert.ToInt32(parent.UserId);
                            walletHistory2.Amount = (od.Amount.Value * 0.1) / 2;
                            walletHistory2.CreateDate = od.Date.Value;
                            walletHistory2.WalletId = 2;
                            walletHistory2.Description = desc;
                            db.WalletHistories.Add(walletHistory2);
                        }
                        //ong noi
                        var grandparent = db.UserProfiles.Where(w => w.UserId == parent.Parent_ID).FirstOrDefault();
                        if (grandparent != null && grandparent.UserName != "root" && grandparent.Status == true)
                        {
                            string desc2 = string.Format("Sponsor commission from reffer user {0}, order {1}.You recieve {2} % of Ph value, floor {3}", user.UserName, od.ID_Order, 3, 2);

                            db.Profits.Add(new LKVMLMLib.Profit()
                            {
                                UserId = grandparent.UserId,
                                PV = 0,
                                Amount = od.Amount.Value * 0.03,
                                CreateDate = od.Date,
                                Decription = desc2,
                                ProfitType = "HoaHongTrucTiep",
                                OrderID = od.ID
                            });
                            var refwallet3 = db.Wallet_Detail.Where(w => w.UserID == grandparent.UserId && w.WalletID == 1).SingleOrDefault();
                            if (refwallet3 != null)
                            {
                                refwallet3.Balance += (double)(od.Amount.Value * 0.03) / 2;
                                var walletHistory = new WalletHistory();
                                walletHistory.UserId = Convert.ToInt32(grandparent.UserId);
                                walletHistory.Amount = (od.Amount.Value * 0.03) / 2;
                                walletHistory.CreateDate = od.Date.Value;
                                walletHistory.WalletId = 1;
                                walletHistory.Description = desc2;
                                db.WalletHistories.Add(walletHistory);
                            }
                            var refwallet4 = db.Wallet_Detail.Where(w => w.UserID == grandparent.UserId && w.WalletID == 2).SingleOrDefault();
                            if (refwallet4 != null)
                            {
                                refwallet4.Balance += (double)(od.Amount.Value * 0.03) / 2;
                                var walletHistory2 = new WalletHistory();
                                walletHistory2.UserId = Convert.ToInt32(grandparent.UserId);
                                walletHistory2.Amount = (od.Amount.Value * 0.03) / 2;
                                walletHistory2.CreateDate = od.Date.Value;
                                walletHistory2.WalletId = 2;
                                walletHistory2.Description = desc2;
                                db.WalletHistories.Add(walletHistory2);
                            }
                            //ong co'
                            var overParent = db.UserProfiles.Where(w => w.UserId == grandparent.Parent_ID).FirstOrDefault();
                            if (overParent != null && overParent.UserName != "root" && overParent.Status == true)
                            {

                                string desc4 = string.Format("Sponsor commission from reffer user {0}, order {1}.You recieve {2} % of Ph value, floor {3}", user.UserName, od.ID_Order, 2, 3);

                                db.Profits.Add(new LKVMLMLib.Profit()
                                {
                                    UserId = overParent.UserId,
                                    PV = 0,
                                    Amount = od.Amount.Value * 0.02,
                                    CreateDate = od.Date,
                                    Decription = desc4,
                                    ProfitType = "HoaHongTrucTiep",
                                    OrderID = od.ID
                                });

                                var refwallet5 = db.Wallet_Detail.Where(w => w.UserID == overParent.UserId && w.WalletID == 1).SingleOrDefault();
                                if (refwallet5 != null)
                                {
                                    refwallet5.Balance += (double)(od.Amount.Value * 0.02) / 2;
                                    var walletHistory = new WalletHistory();
                                    walletHistory.UserId = Convert.ToInt32(overParent.UserId);
                                    walletHistory.Amount = (od.Amount.Value * 0.02) / 2;
                                    walletHistory.CreateDate = od.Date.Value;
                                    walletHistory.WalletId = 1;
                                    walletHistory.Description = desc4;
                                    db.WalletHistories.Add(walletHistory);
                                }
                                var refwallet6 = db.Wallet_Detail.Where(w => w.UserID == overParent.UserId && w.WalletID == 2).SingleOrDefault();
                                if (refwallet6 != null)
                                {
                                    refwallet6.Balance += (double)(od.Amount.Value * 0.02) / 2;
                                    var walletHistory2 = new WalletHistory();
                                    walletHistory2.UserId = Convert.ToInt32(overParent.UserId);
                                    walletHistory2.Amount = (od.Amount.Value * 0.02) / 2;
                                    walletHistory2.CreateDate = od.Date.Value;
                                    walletHistory2.WalletId = 2;
                                    walletHistory2.Description = desc4;
                                    db.WalletHistories.Add(walletHistory2);
                                }
                            }
                        }
                    }
                    db.SaveChanges();
                }
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
            {
                Exception raise = dbEx;
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        string message = string.Format("{0}:{1}",
                            validationErrors.Entry.Entity.ToString(),
                            validationError.ErrorMessage);
                        raise = new InvalidOperationException(message, raise);
                    }
                }
                throw raise;
            }

        }
        public bool createTransferOrder(int ghID = 0, int phId = 0, int userSend = 0, int userRecieve = 0, double Amount = 0, string Desc = "")
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                try
                {
                    var to = new TransferOrder();
                    to.Gh_Id = ghID;
                    to.Ph_Id = phId;
                    to.GH_Mobile = db.UserProfiles.Where(w => w.UserId == userRecieve).FirstOrDefault() != null ?
                                   db.UserProfiles.Where(w => w.UserId == userRecieve).FirstOrDefault().SDTNHARIENG : "";
                    to.PH_Mobile = db.UserProfiles.Where(w => w.UserId == userSend).FirstOrDefault() != null ?
                                   db.UserProfiles.Where(w => w.UserId == userSend).FirstOrDefault().SDTNHARIENG : "";
                    to.UserGH = userRecieve;
                    to.UserPH = userSend;
                    to.PH_Name = db.UserProfiles.Where(w => w.UserId == userSend).FirstOrDefault() != null ?
                                   db.UserProfiles.Where(w => w.UserId == userSend).FirstOrDefault().UserName : "";
                    to.GH_Name = db.UserProfiles.Where(w => w.UserId == userRecieve).FirstOrDefault() != null ?
                                   db.UserProfiles.Where(w => w.UserId == userRecieve).FirstOrDefault().UserName : "";
                    to.CreateDate = DateTime.Now;
                    to.Amount = Amount;
                    to.Description = Desc;
                    to.Status = 0;
                    db.TransferOrders.Add(to);
                    db.SaveChanges();
                    return true;
                }
                catch (Exception em) { return false; }
            }
        }
    }
    public class HtmlHelperExtensions
    {
        public static string generateRandomString(int length = 0, int isAlphanumeric = 0)
        {
            string alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            string small_alphabets = "abcdefghijklmnopqrstuvwxyz";
            string numbers = "1234567890";

            string characters = numbers;
            if (isAlphanumeric == 1)
            {
                characters += alphabets + small_alphabets + numbers;
            }
            string otp = string.Empty;
            for (int i = 0; i < length; i++)
            {
                string character = string.Empty;
                do
                {
                    int index = new Random().Next(0, characters.Length);
                    character = characters.ToCharArray()[index].ToString();
                } while (otp.IndexOf(character) != -1);
                otp += character;
            }
            return otp;
        }
    }
}